package com.duckygo.towerdefense.game.sprites;

import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11Ext;

import android.view.animation.Animation.AnimationListener;

import com.duckygo.towerdefense.game.TextureManager;
import com.duckygo.towerdefense.game.scenes.SceneManager;

public class AnimatedSprite2D extends Sprite2D {

	public class AnimationTemplate {
		
		public int fps;
		
		public int frameCount;
		
		public int offsetX;
		public int offsetY;
		
		public boolean loop;
	}

	
	public class AnimationRunnable {
		
		public AnimationListener listener;
		
		private int frameIdx = 0;
		
		private Timer timer;
		
		public AnimationRunnable(final AnimationTemplate template, final AnimatedSprite2D sprite, final boolean loop) {
			timer = new Timer();
			timer.scheduleAtFixedRate(new TimerTask() {

				@Override
				public void run() {
					sprite.cropX = template.offsetX + frameIdx * sprite.width;
					sprite.cropY = template.offsetY;
					
					frameIdx++;
					
					if (frameIdx >= template.frameCount) {
						if (template.loop || loop) {
							if (listener != null) listener.onAnimationRepeat(null);
							frameIdx = 0;
						} else {
							stop();
						}
					}
				}
				
			}, 0, 1000 / template.fps);
		}

		protected void stop() {
			if (listener != null) listener.onAnimationEnd(null);
			timer.cancel();
		}
	}
	
	
	protected Hashtable<String, AnimationTemplate> getAnimations() {
		return null;
	}

	
	protected int textureHeight;
	
	
	public AnimatedSprite2D() {
	}
	
	public void registerAnimation(String name, int fps, int frameCount, int cropX, int cropY) {
		AnimationTemplate template = new AnimationTemplate();
		template.fps = fps;
		template.frameCount = frameCount;
		template.offsetX = cropX;
		template.offsetY = cropY;
		
		getAnimations().put(name, template);
		
	}
	
	
	public AnimationRunnable play(String animation, boolean loop) {
		AnimationTemplate template = getAnimations().get(animation);
		if (template == null) {
			return null;
		}
		
		return new AnimationRunnable(template, this, loop);
	}
	
}
